<template>
	<div class="app-container">
		<div class="table-wrapper">
			<h4>建筑物易损性信息</h4>
			<!-- 编辑 -->
			<el-form :inline="true" ref="formRef" :rules="rules" label-position="right" :model="params" label-width="200px">
				<div class="form-inline">
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="编号：" class="form-item" prop="number"><el-input v-model="params.number"
									placeholder="" clearable disabled /></el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="用途：">
								<el-col :span="12">
									<el-form-item prop="use0">
										<el-select v-model="params.use0" placeholder="请选择" class="form-select"
											@change="useChange" clearable disabled>
											<el-option v-for="item in useOptions" :key="item.value" :label="item.label"
												:value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
								<el-col :span="11">
									<el-form-item prop="use1">
										<el-select v-model="params.use1" placeholder="请选择" class="form-select" clearable
											disabled>
											<el-option v-for="item in use1Options" :key="item.value" :label="item.label"
												:value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="区域：" class="form-item" prop="region">
								<el-form-item prop="province" style="width:120px;margin-right:10px;">
									<el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince"
										clearable disabled value-key="id">
										<el-option v-for="item in provinceData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item prop="city" style="width:120px;margin-right:10px;">
									<el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable
										disabled value-key="id">
										<el-option v-for="item in cityData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
								<el-form-item prop="county" style="width:120px;">
									<el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable
										disabled value-key="id">
										<el-option v-for="item in areaData" :key="item.id" :label="item.name"
											:value="item"></el-option>
									</el-select>
								</el-form-item>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="结构类型：" class="form-item" prop="structureType">
								<el-col :span="12">
									<el-form-item prop="structureType">
										<el-select v-model="params.structureType" placeholder="请选择" class="form-select"
											@change="structureTypeChange" clearable disabled>
											<el-option v-for="item in structureTypeOptions" :key="item.value"
												:label="item.label" :value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
								<el-col :span="11">
									<el-form-item prop="structureType1">
										<el-select v-model="params.structureType1" placeholder="请选择" class="form-select"
											clearable disabled>
											<el-option v-for="item in structureType1Options" :key="item.value"
												:label="item.label" :value="item.value"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="设防情况：" class="form-item" prop="fortification">
								<el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable
									disabled>
									<el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
										:value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item label="建造年代：" class="form-item" prop="years">
								<el-select v-model="params.years" placeholder="请选择" class="form-select" clearable disabled>
									<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
										:value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="11">
							<el-form-item label="维护人：" class="form-item" prop="userName"><el-input v-model="params.userName"
									placeholder="" clearable disabled /></el-form-item>
						</el-col>
						<el-col :span="11">
							<el-form-item prop="createTime" label="维护时间:">
								<el-date-picker clearable disabled v-model="params.createTime" type="date"
									placeholder="开始时间" value-format="YYYY-MM-DD" />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="22">
							<el-form-item label="维护人所属单位：" class="form-item" prop="maintainerUnit" style="width: 100%;">
								<el-input v-model="params.maintainerUnit" placeholder="" clearable disabled />
							</el-form-item>
						</el-col>
					</el-row>
					<el-row justify="center">
						<el-col :span="22">
							<el-form-item label="备注：" class="form-item" prop="damage" style="width: 100%;">
								<el-input type="textarea" v-model="params.damage" placeholder="" clearable disabled />
							</el-form-item>
						</el-col>
					</el-row>
				</div>
			</el-form>

			<h4>地震易损性矩阵</h4>
			<el-table class="listTables" ref="multipleTableRef" border :data="tableData" style="width: 100%"
				:cell-style="{ border: '1px solid #e5ebf7' }"
				:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
				<el-table-column prop="damage" label="破坏程度" align="right" width="150"><el-table-column prop="intensity"
						label="烈度" width="150"></el-table-column></el-table-column>
				<el-table-column header-align="center" align="center" label="基本完好">
					<template #default="scope">
						<span>{{ scope.row.bs }}</span>
					</template>
				</el-table-column>

				<el-table-column header-align="center" align="center" label="轻微破坏">
					<template #default="scope">
						<span>{{ scope.row.sl }}</span>
					</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="中等破坏">
					<template #default="scope">
						<span>{{ scope.row.ml }}</span>
					</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="严重破坏">
					<template #default="scope">
						<span>{{ scope.row.el }}</span>
					</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="倒塌">
					<template #default="scope">
						<span>{{ scope.row.c }}</span>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<!-- echarts图表 -->
		<div v-if="showBarChart" class="seismic-fragility-bar"></div>
		<div v-if="showLineChart" class="seismic-fragility-line"></div>
	</div>
</template>

<script setup>
import { computed, reactive, toRefs } from 'vue';
// 状态管理模块
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 获取用户信息
import { getInfo } from '@/api/login';
// 引入接口
import {
	getDataById, //回显
} from '@/api/buildingVulnerAnalysis/buildingVulnerAnalysis.js';
import { getProvince, getChildArea } from '@/api/system/division';
import * as echarts from 'echarts';


// 获取当前实例
const { proxy } = getCurrentInstance();
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 全局路由对象
const router = useRouter();
// 当前路由对象
const route = useRoute();

// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');
// 表单对象
const formRef = ref();

// 图表显示隐藏控制
let showBarChart = ref(true);
let showLineChart = ref(true);

const data = reactive({
	// 表单参数
	params: {
		number: '', //编号
		use0: '', //用途
		use1: '', //用途
		region: '', //区域
		province: '', //省
		city: '', //市
		county: '', //区县
		structureType: '', //结构类型
		structureType1: '',
		cs: '', //层数
		years: '', //建造年代
		fortification: '', //设防情况
		userName: '', //维护人
		createTime: '', //维护时间
		maintainerUnit: '', //维护人所属单位
		remarks: '', //备注
	},
	// 表单验证规则
	rules: {
		// number: [{ required: true, message: '请选择', trigger: 'blur' }],
		fortification: [{ required: true, message: '请选择', trigger: 'change' }],
		years: [{ required: true, message: '请选择', trigger: 'change' }],
		province: [{ required: true, message: '请选择', trigger: 'change' }],
		structureType: [{ required: true, message: '请选择', trigger: 'change' }]
	},
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 年份
	yearsOptions: dictStore.yearsOptions || [],
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions || [],
	structureType1Options: [],
	// 用途
	useOptions: dictStore.useOptions || [],
	use1Options: [],
	use0Label: '',
	use1Label: '',
	//表格
	tableData: [
		{
			bs: '',
			sl: '',
			ml: '',
			el: '',
			c: ''
		}
	]
});
const {
	// 表单数据
	params,
	// 表单验证规则
	rules,
	// 设防情况选项
	fortificationOptions,
	// 年份选项
	yearsOptions,
	// 结构类型选项
	structureTypeOptions,
	structureType1Options,
	// 用途选项
	useOptions,
	use1Options,
	// 当前用途
	use0Label,
	use1Label,
	// 表格数据
	tableData,
} = toRefs(data);

/* 
	根据值获取用途
	params: {
		key: 值
	}
 */
function getUseByOptions(key) {
	const use = useOptions.value.find(item => item.value == key);
	return use ? (use.label || '') : '';
}
/* 
	根据值获取子用途
	params: {
		key1: 一级值
		key2: 二级值
	}
 */
function getChildUseByOptions(key1, key2) {
	const use = useOptions.value.find(item => item.value == key1);
	let childUse = {};
	if (use && use.children) {
		childUse = use.children.find(item => item.value == key2);
	}
	return childUse ? (childUse.label || '') : '';
}

// 行政区划选择
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
// 获取省份数据
function getProvinceData() {
	getProvince().then(response => {
		provinceData.value = response.data;
	});
}
// 选择省份
function chooseProvince(value) {
	params.value.city = null;
	params.value.county = null;
	params.value.province = value.name;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value.id).then(response => {
		cityData.value = response.data;
	});
}
// 选择城市
function chooseCity(value) {
	params.value.city = value.name;
	params.value.county = null;
	areaData.value = [];
	getChildArea(value.id).then(response => {
		areaData.value = response.data;
	});
}
// 选择区县
function chooseCounty(value) {
	params.value.county = value.name;
}

// 结构类型选择
const structureTypeChange = val => {
	const structureTypes = structureTypeOptions.value.find(item => item.value === val);
	if (structureTypes) {
		params.value.structureType1 = '';
		structureType1Options.value = structureTypes.children;
	}
};
// 选择用途
const useChange = val => {
	const use = useOptions.value.find(item => item.value === val);
	if (use) {
		params.value.use1 = '';
		use1Options.value = use.children;
	}
};

//地震易损性矩阵表格查询
const onSearch = () => {
	const query = {
		number: route.query.number,
		dataType: route.query.dataType,
		cbhdId: route.query.cbhdId,
		operate: route.query.operate
	};
	getDataById(query).then(res => {
		if (res.code === 200 && res.data) {
			tableData.value = [];
			const { data } = res.data;
			if (data && JSON.stringify(data) != '{}') {
				// 渲染表格
				bulidTable(res.data.data);
			} else {
				proxy.$modal.msgWarning('建筑物易损性信息获取失败！');
			}
			// 用途
			use0Label.value = getUseByOptions(params.use0);
			use1Label.value = getChildUseByOptions(params.use0, params.use1);
			// 判断没数据不显示图表
			const { histogram } = res.data;
			if (histogram && JSON.stringify(histogram) != '{}') {
				// 渲染柱状图
				buildChartBar(res.data.histogram);
			} else {
				// 隐藏柱状图区域
				showBarChart.value = false;
			}
			const { curve } = res.data;
			if (curve && !(JSON.stringify(curve.sd) == '{}' && JSON.stringify(curve.md) == '{}' && JSON.stringify(curve.ed) == '{}' && JSON.stringify(curve.c) == '{}')) {
				// 渲染折线图
				buildChartLine(res.data.curve);
			} else {
				// 隐藏折线图区域
				showLineChart.value = false;
			}
		}
	}).catch(err => {
		console.log(err);
	});
};
// 获取用户
function getUserInfo(userId) {
	getInfo(userId).then(response => {
		params.value.userName = response.user.userName
		params.value.maintainerUnit = response.user.orgName
		//params.value.createTime = parseTime(new Date())
	});
};

//保存
const onSave = async (formEl) => {
	if (!formEl) return;
	// 表单验证
	await formEl.validate((valid, fields) => {
		if (valid) {
			proxy.$modal.msg('保存');
		} else {
			proxy.$modal.msgWarning('表单验证失败，请检测填写数据！');
		}
	})
};
//重置
const onRest = (formEl) => {
	// 重置表单，方式一
	formEl.resetFields();
	// 重置表单，方式二
	// proxy.resetForm('formRef');
};

//表格
const bulidTable = data => {
	const arrKeys = Object.keys(data).sort((a, b) => parseInt(a) > parseInt(b) ? 1 : -1);
	for (const index in arrKeys) {
		const key = arrKeys[index];
		const element = data[key];
		if (element) {
			const item = {
				isEdit: false,
				intensity: key,
				bs: 0,
				sl: 0,
				ml: 0,
				el: 0,
				c: 0
			};
			if (element['基本完好']) {
				item.bs = element['基本完好'][0].paramValue;
			}
			if (element['轻微破坏']) {
				item.sl = element['轻微破坏'][0].paramValue;
			}
			if (element['中等破坏']) {
				item.ml = element['中等破坏'][0].paramValue;
			}
			if (element['严重破坏']) {
				item.el = element['严重破坏'][0].paramValue;
			}
			if (element['倒塌']) {
				item.c = element['倒塌'][0].paramValue;
			}
			tableData.value.push(item);
			for (const key1 in element) {
				if (element[key1] && element[key1][0] && index == 0) {
					params.value = element[key1][0];
					if (params.value.createUser) {
						// 获取用户
						getUserInfo(params.value.createUser);
					}
				}
			}
		}
	}
};

// 图表
let m_chartBar = null;
let m_chartLine = null;
//柱状图
const buildChartBar = data => {
	if (!m_chartBar) {
		m_chartBar = echarts.init(document.querySelector('.seismic-fragility-bar'));
	}
	const xAxisData = [];
	const bsData = [];
	const slData = [];
	const mlData = [];
	const elData = [];
	const cData = [];
	const arrKeys = Object.keys(data).sort((a, b) => parseInt(a) > parseInt(b) ? 1 : -1);
	if (arrKeys && arrKeys.length) {
		for (const index in arrKeys) {
			const key = arrKeys[index];
			const element = data[key];
			xAxisData.push(key);
			bsData.push(element['基本完好'] || 0);
			slData.push(element['轻微破坏'] || 0);
			mlData.push(element['中等破坏'] || 0);
			elData.push(element['严重破坏'] || 0);
			cData.push(element['倒塌'] || 0);
		}
	}
	const option = {
		toolbox: {
			//echart保存为图片
			show: true,
			feature: {
				mark: {
					show: true
				},
				restore: {
					show: true
				},
				saveAsImage: {
					show: true,
					pixelRatio: 1,
					title: '保存为图片',
					type: 'png',
					lang: ['点击保存']
				}
			}
		},
		tooltip: {
			trigger: 'axis',
			axisPointer: {
				type: 'shadow'
			}
		},
		legend: {},
		xAxis: {
			name: '地震烈度',
			type: 'category',
			data: xAxisData
		},
		yAxis: {
			name: '超越概率',
			type: 'value',
			axisLabel: {
				formatter: '{value}%'
			}
		},
		series: [
			{
				name: '基本完好',
				type: 'bar',
				barWidth: '40', //设置柱宽度
				stack: 'Ad',
				emphasis: {
					focus: 'series'
				},
				data: bsData
			},
			{
				name: '轻微破坏',
				type: 'bar',
				stack: 'Ad',
				emphasis: {
					focus: 'series'
				},
				data: slData
			},
			{
				name: '中等破坏',
				type: 'bar',
				stack: 'Ad',
				emphasis: {
					focus: 'series'
				},
				data: mlData
			},
			{
				name: '严重破坏',
				type: 'bar',
				stack: 'Ad',
				emphasis: {
					focus: 'series'
				},
				data: elData
			},
			{
				name: '倒塌',
				type: 'bar',
				stack: 'Ad',
				emphasis: {
					focus: 'series'
				},
				data: cData
			}
		]
	};
	m_chartBar.clear();
	m_chartBar.setOption(option, true);
};
//折线图
const buildChartLine = data => {
	if (!m_chartLine) {
		m_chartLine = echarts.init(document.querySelector('.seismic-fragility-line'));
	}
	const xAxisData = Object.keys(data.c);
	const cData = Object.values(data.c);
	const edData = Object.values(data.ed);
	const mdData = Object.values(data.md);
	const sdData = Object.values(data.sd);
	const option = {
		toolbox: {
			//echart保存为图片
			show: true,
			feature: {
				mark: {
					show: true
				},
				restore: {
					show: true
				},
				saveAsImage: {
					show: true,
					pixelRatio: 1,
					title: '保存为图片',
					type: 'png',
					lang: ['点击保存']
				}
			}
		},
		legend: {
			data: ['c', 'ed', 'md', 'sd']
		},
		tooltip: {
			trigger: 'axis'
		},
		xAxis: {
			name: 'PGA:(IM)',
			type: 'category',
			data: xAxisData
		},
		yAxis: {
			name: '超越概率',
			type: 'value',
			axisLabel: {
				formatter: '{value}%'
			}
		},
		series: [
			{
				name: 'c',
				data: cData,
				smooth: true,
				type: 'line'
			},
			{
				name: 'ed',
				data: edData,
				smooth: true,
				type: 'line'
			},
			{
				name: 'md',
				data: mdData,
				smooth: true,
				type: 'line'
			},
			{
				name: 'sd',
				data: sdData,
				smooth: true,
				type: 'line'
			}
		]
	};
	m_chartLine.clear();
	m_chartLine.setOption(option, true);
};

// 挂载后
onMounted(() => {
	// 获取行政区划数据
	getProvinceData();
	// 初始化获取数据
	onSearch();
});
// 卸载前
onBeforeUnmount(() => {
	if (m_chartBar) {
		m_chartBar.dispose();
		m_chartBar = null;
	}
	if (m_chartLine) {
		m_chartLine.dispose();
		m_chartLine = null;
	}
});
</script>

<style lang="scss" scoped>
.table-wrapper {
	position: relative;

	h4 {
		font-size: 16px;
		font-weight: bold;
		color: #107ce5;
		text-align: center;
	}
}

.form-inline {
	.el-form-item {
		margin-right: 0;
	}
}

:deep(.el-table.listTables) {
	thead.is-group th {
		background: none;
	}

	thead.is-group tr:first-of-type th:first-of-type {
		border-bottom: none;
	}

	thead.is-group tr:first-of-type th:first-of-type:before {
		content: '';
		position: absolute;
		width: 1px;
		height: 85px;
		/*这里需要自己调整，根据td的宽度和高度*/
		top: 0;
		left: 0;
		background-color: grey;
		opacity: 0.3;
		display: block;
		transform: rotate(302deg);
		/*这里需要自己调整，根据线的位置*/
		transform-origin: top;
	}

	thead.is-group tr:last-of-type th:first-of-type:before {
		content: '';
		position: absolute;
		width: 1px;
		height: 88px;
		/*这里需要自己调整，根据td的宽度和高度*/
		bottom: 0;
		right: 0;
		background-color: grey;
		opacity: 0.3;
		display: block;
		transform: rotate(302deg);
		/*这里需要自己调整，根据线的位置*/
		transform-origin: bottom;
		/* background:red; */
	}
}

// 图表样式
.seismic-fragility-bar,
.seismic-fragility-line {
	width: 100%;
	height: 400px;
	margin: 20px auto;
}
</style>
